import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from "./../components/login.vue"
import Home from "./../components/home.vue"
import Welcome from "./../components/Welcome.vue"
import user from "./../components/user/user.vue"
Vue.use(VueRouter)

const routes = [
  // 访问路径 / 重定向到login
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: Welcome },
      { path: '/users', component: user }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 代表从哪个路径跳转而来
  // next 是一个函数 表示放行  next()放行  next('/login') 强制跳转

  // 访问登录页直接放行
  if (to.path === '/login') return next();

  // 判断token是否存在  不存在直接跳转到登录页面
  const tokenStr = sessionStorage.getItem("token")
  if (!tokenStr) return next("/login")

  // 如果以上条件都不满足 证明token存在 直接放行
  next()
})

export default router
